package edu.whu.assignment8.service.impl;

import edu.whu.assignment8.dataobject.Product;
import edu.whu.assignment8.dataobject.User;
import edu.whu.assignment8.dataobject.UserProduct;
import edu.whu.assignment8.mapper.ProductMapper;
import edu.whu.assignment8.mapper.UserMapper;
import edu.whu.assignment8.mapper.UserProductMapper;
import edu.whu.assignment8.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserProductMapper userProductMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public User findById(int uid) {
        return userMapper.selectById(uid);
    }

    @Override
    public int registration(User user) {
        User same = userMapper.selectByUsername(user.getUsername());
        if(same != null) {
            return -1;  //-1表示有同名的用户，需要重新填写
        }
        return userMapper.insert(user);
    }

    @Override
    public int login(User user) {
        User exist = userMapper.selectByUsername(user.getUsername());
        if(exist == null) {
            return -1; //表示用户不存在
        }
        if(exist.getPassword().equals(user.getPassword())) {
            return 1;
        }
        else {
            return 0;
        }
    }

    @Override
    public List<User> findAll() {
        return userMapper.selectList(null);
    }

    @Override
    public int buyProduct(int uid, int pid) {
        User existUser = userMapper.selectById(uid);
        Product existProduct = productMapper.selectById(pid);
        if(existUser == null || existProduct == null) {
            return -1;
        }
        UserProduct userProduct = new UserProduct();
        userProduct.setUid(uid);
        userProduct.setPid(pid);
        return userProductMapper.insert(userProduct);
    }
}
